package models

import (
	"gorm.io/gorm"
)

type OrderItem struct {
	ID                 int      `json:"id" gorm:"primarykey"`
	OrderID            uint     `json:"order_id"`
	ProductID          uint     `json:"product_id" binding:"required"`
	Number             int      `json:"number" binding:"required"`
	OriginalPrice      float32  `json:"original_price"`
	ActualPrice        float32  `json:"actual_price"`
	Product            Product  `json:"product" gorm:"-"`
	ProductSnapShoot   string   `json:"product_snap_shoot"`
	OriginalTotalPrice float32  `json:"original_total_price"`
	ActualTotalPrice   float32  `json:"actual_total_price"`
	db                 *gorm.DB `json:"-"`
}

func (OrderItem) TableName() string {
	return "order_items"
}
func (p *OrderItem) BeforeCreate(tx *gorm.DB) (err error) {
	return nil
}
func (p *OrderItem) Create(c *OrderItem) (*OrderItem, error) {
	result := p.db.Create(c)
	if result.Error != nil {
		return nil, result.Error
	}
	return c, nil
}

func (p *OrderItem) Update(c *OrderItem) (*OrderItem, error) {
	result := p.db.Updates(c)
	if result.Error != nil {
		return nil, result.Error
	}
	return c, nil
}

func (p *OrderItem) Delete(order_itemId int) error {
	result := p.db.Delete(&OrderItem{}, order_itemId)
	return result.Error
}

func (p *OrderItem) FindByID(order_item_id int) (model *OrderItem, err error) {
	model = &OrderItem{}
	model.ID = order_item_id
	result := p.db.First(model)
	err = result.Error
	return
}

func (p OrderItem) FindByUserID(page, rows int, user_id uint) (pages *Pages, error error) {
	var data []OrderItem
	var all int64
	pages = &Pages{}
	query := p.db.Model(OrderItem{}).Where("user_id = ?", user_id)
	//all
	result := query.Count(&all)
	if result.Error != nil {
		return nil, result.Error
	}
	query.Limit(rows).Offset((page - 1) * rows).Find(&data)
	result = query.Count(&all)
	if result.Error != nil {
		return nil, result.Error
	}
	return NewPages(page, rows, all, data), nil
}

type IOrderItem interface {
	FindByID(orderItemId int) (*OrderItem, error)
	FindByUserID(page, rows int, userId uint) (pages *Pages, error error)
	Create(c *OrderItem) (*OrderItem, error)
	Update(c *OrderItem) (*OrderItem, error)
	Delete(orderItemId int) error
}

func NewOrderItem(db *gorm.DB) IOrderItem {
	return &OrderItem{db: db}
}
